//
//  UIViewController+ACNavbar.m
//  ACFramework
//
//  Created by caoyq on 2018/5/23.
//

#import "UIViewController+ACNavbar.h"
#import <objc/runtime.h>
#import "sys/sysctl.h"

@interface UIViewController ()

@property (strong, nonatomic) UIScrollView *keyScrollView;

///最大滚动偏移量，超过则透明度不再随着滚动而改变
@property (assign, nonatomic) CGFloat maxOffsetY;

///收集导航栏上透明度可改变的标签
@property (assign, nonatomic) HCHidenControlOptions options;

@end

@implementation UIViewController (ACNavbar)

#pragma mark - public

- (void)ac_addKeyScrollView:(UIScrollView *)keyScrollView MaxOffsetY:(CGFloat)maxOffsetY Options:(HCHidenControlOptions)options {
    self.keyScrollView = keyScrollView;
    self.maxOffsetY = maxOffsetY;
    self.options = options;
    [self.keyScrollView addObserver: self forKeyPath: @"contentOffset" options: NSKeyValueObservingOptionNew context:nil];
}

#pragma mark - 通过运行时动态添加存储属性

//定义关联的 keyScrollView
static const char * key = "keyScrollView";
- (UIScrollView *)keyScrollView{
    
    return objc_getAssociatedObject(self, key);
}

- (void)setKeyScrollView:(UIScrollView *)keyScrollView{
    objc_setAssociatedObject(self, key, keyScrollView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

//定义关联的 scrolOffsetY
static const char * maxOffsetYKey = "maxOffsetY";
- (CGFloat)maxOffsetY{
    
    return [objc_getAssociatedObject(self, maxOffsetYKey) floatValue];
}

- (void)setMaxOffsetY:(CGFloat)maxOffsetY{
    
    objc_setAssociatedObject(self, maxOffsetYKey, @(maxOffsetY), OBJC_ASSOCIATION_ASSIGN);
}

//定义关联的 hc_hidenControlOptions
static const char * optionsKey = "options";
- (NSInteger)options{
    
    return [objc_getAssociatedObject(self,optionsKey) integerValue];
}

- (void)setOptions:(NSInteger)options{
    
    objc_setAssociatedObject(self, optionsKey, @(options), OBJC_ASSOCIATION_ASSIGN);
}

#pragma mark - KVO实现

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    CGFloat maxScrollOffsetY = self.maxOffsetY;
    
    CGFloat offset = self.keyScrollView.contentOffset.y;
    
    CGFloat alpha = offset/maxScrollOffsetY;
    alpha = MIN(1, MAX(0, alpha));
    
    //设置导航条上的标签跟着透明度改变(可以选择不透明)
    self.navigationItem.leftBarButtonItem.customView.alpha = self.options & HCHidenControlOptionLeft ? alpha : 1;
    
    self.navigationItem.titleView.alpha = self.options & HCHidenControlOptionTitle ? alpha : 1;
    
    self.navigationItem.rightBarButtonItem.customView.alpha = self.options & HCHidenControlOptionRight ? alpha : 1;
    
    //设置导航条背景跟着透明度改变
    [[[self.navigationController.navigationBar subviews]objectAtIndex:0] setAlpha:alpha];
}

@end
